package com.example.cinema.service;

import com.example.cinema.model.Schedule;
import com.example.cinema.model.Seat;
import com.example.cinema.model.Ticket;
import com.example.cinema.repository.ScheduleRepository;
import com.example.cinema.repository.SeatRepository;
import com.example.cinema.repository.TicketRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TicketService {

    private final TicketRepository ticketRepository;
    private final SeatRepository seatRepository;
    private final ScheduleRepository scheduleRepository;

    @Autowired
    public TicketService(TicketRepository ticketRepository, SeatRepository seatRepository, ScheduleRepository scheduleRepository) {
        this.ticketRepository = ticketRepository;
        this.seatRepository = seatRepository;
        this.scheduleRepository = scheduleRepository;
    }

    // 购买电影票
    @Transactional
    public Ticket purchaseTicket(Integer scheduleId, Integer rowNo, Integer colNo, String phone) {
        // 1. 检查排片是否存在
        Schedule schedule = scheduleRepository.findById(scheduleId)
                .orElseThrow(() -> new RuntimeException("排片不存在: " + scheduleId));

        // 2. 检查座位是否存在且可售
        Seat seat = seatRepository.findByScheduleIdAndRowNoAndColNo(scheduleId, rowNo, colNo)
                .orElseThrow(() -> new RuntimeException("座位不存在: 排片ID=" + scheduleId + ", 行=" + rowNo + ", 列=" + colNo));

        // 3. 检查座位是否已售出
        if (seat.getSold()) {
            throw new RuntimeException("座位已售出: 排片ID=" + scheduleId + ", 行=" + rowNo + ", 列=" + colNo);
        }

        // 4. 检查是否已有人购买该座位（防止并发问题）
        ticketRepository.findByScheduleIdAndRowNoAndColNo(scheduleId, rowNo, colNo)
                .ifPresent(ticket -> {
                    throw new RuntimeException("座位已被购买: 排片ID=" + scheduleId + ", 行=" + rowNo + ", 列=" + colNo);
                });

        // 5. 更新座位状态为已售
        seat.setSold(true);
        seatRepository.save(seat);

        // 6. 创建购票记录
        Ticket ticket = new Ticket(schedule, rowNo, colNo, phone);
        return ticketRepository.save(ticket);
    }

    // 获取所有已售出的票
    public List<Ticket> getAllTickets() {
        return ticketRepository.findAll();
    }
}